<?php
namespace app\wx\model;

Class Qywx
{
    //获取企业微信应用服务商token,返回对象，provider_access_token，expires_in
    function get_provider_token()
    {
        $wx_config=config('wx');
        $data['corpid']=$wx_config['corpid'];
        $data['provider_secret']=$wx_config['providersecret'];
        $data=json_encode($data);
        $res=model('Http')->httpPost('https://qyapi.weixin.qq.com/cgi-bin/service/get_provider_token',$data);
        return $res;
        /*返回示例
        {
           "errcode":0 ,
           "errmsg":"ok" ,
           "provider_access_token":"enLSZ5xxxxxxJRL",
           "expires_in":7200
        }
        */
    }


    /**获取登录的企业用户信息，返回对象
     * @param string $auth_code 跳转企业微信传入的授权码
     * @return array
     */
    function get_login_info($auth_code='')
    {
        if($auth_code=='')
        {
            return ['res'=>false,'msg'=>'auth_code不能为空'];
        }
        $token=$this->get_provider_token();
        $token=json_decode($token);
        $data['auth_code']=$auth_code;
        $data=json_encode($data);
        $res=model('Http')->httpPost('https://qyapi.weixin.qq.com/cgi-bin/service/get_login_info?access_token='.$token->provider_access_token,$data);
        return $res;
        /*返回示例
        {
           "errcode":0,
           "errmsg":"ok",
           "usertype": 1,
           "user_info":{
               "userid":"xxxx",
               "name":"xxxx",
               "avatar":"xxxx"
               "email":"xxxx"
           },
           "corp_info":{
               "corpid":"wx6c698d13f7a409a4",
            },
           "agent":[
               {"agentid":0,"auth_type":1},
               {"agentid":1,"auth_type":1},
               {"agentid":2,"auth_type":1}
           ],
           "auth_info":{
               "department":[
                   {
                       "id":"2",
                       "writable":"true"
                   }
               ]
           }
        }
        */
    }

    //获取应用凭证,该API用于获取应用凭证（suite_access_token）。
    //$app=应用配置前缀简称，例如 ams mss
    function get_suite_token($app='')
    {

        $wx_config=config('wx');
        $data['suite_id']=$wx_config[$app.'_SuiteID'];
        $data['suite_secret']=$wx_config[$app.'_Secret'];

        $suite_con=db('suite_config')->where('app',$app)->find();
        $data['suite_ticket']=$suite_con['suiteticket'];
        $data=json_encode($data);
        $res=model('Http')->httpPost('https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token',$data);
        return $res;
        /*返回的示例
        {
            "suite_access_token":"61W3mEpU66027wgNZ_MhGHNQDHnFATkDa9-2llqrMBjUwxRSNPbVsMmyD-yq8wZETSoE5NQgecigDrSHkPtIYA",
            "expires_in":7200
        }
        */
    }

    //获取预授权码，该API用于获取预授权码。预授权码用于企业授权时的第三方服务商安全验证。
    function get_pre_auth_code()
    {

        $token=$this->get_suite_token();
        $token=json_decode($token);
        if($token->suite_access_token=='')
        {
            return false;
        }
        $wx_config=config('wx');
        $data['suite_id']=$wx_config['suite_id'];
        $data=json_encode($data);
        $res=model('Http')->httpPost('https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token='.$token->suite_access_token,$data);
        return $res;
        /*返回示例
        {
            "errcode":0 ,
            "errmsg":"ok" ,
            "pre_auth_code":"Cx_Dk6qiBE0Dmx4EmlT3oRfArPvwSQ-oa3NL_fwHM7VI08r52wazoZX2Rhpz1dEw",
            "expires_in":1200
        }
        */
    }

    //获取注册码,该API用于根据注册模板生成注册码（register_code）。
    function get_register_code()
    {
        $token=$this->get_provider_token();
        $token=json_decode($token);
        if($token->provider_access_token=='')
        {
            return false;
        }
        $data=json_encode([]);
        $res=model('Http')->httpPost('https://qyapi.weixin.qq.com/cgi-bin/service/get_register_code?provider_access_token='.$token->provider_access_token,$data);
        return $res;
        /*返回示例
        {
            "errcode":0,
            "errmsg":"ok",
            "register_code":"pIKi3wRPNWCGF-pyP-YU5KWjDDD",
            "expires_in": 600
        }
        */
    }

    //获取企业永久授权码，该API用于使用临时授权码换取授权方的永久授权码，并换取授权信息、企业access_token，临时授权码一次有效。建议第三方优先以userid或手机号为主键、其次以email为主键来建立自己的管理员账号。
    //$app=应用配置前缀简称，例如 ams mss
    //$auth_code=临时授权码
    function get_permanent_code($app='',$auth_code='')
    {
        if($auth_code==''||$app=='')
        {
            return false;
        }
        $token=$this->get_suite_token($app);
        $token=json_decode($token);
        if($token->suite_access_token=='')
        {
            return false;
        }
        $wx_config=config('wx');
        $data['suite_id']=$wx_config[$app.'_SuiteID'];
        $data['auth_code']=$auth_code;
        $data=json_encode($data);
        $res=model('Http')->httpPost('https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token='.$token->suite_access_token,$data);
        return $res;
        /*返回示例
        {
            "errcode":0 ,
            "errmsg":"ok" ,
            "access_token": "xxxxxx",
            "expires_in": 7200,
            "permanent_code": "xxxx",
            "auth_corp_info":
            {
                "corpid": "xxxx",
                "corp_name": "name",
                "corp_type": "verified",
                "corp_square_logo_url": "yyyyy",
                "corp_user_max": 50,
                "corp_agent_max": 30,
                "corp_full_name":"full_name",
                "verified_end_time":1431775834,
                "subject_type": 1，
                "corp_wxqrcode": "zzzzz"
            },
            "auth_info":
            {
                "agent" :
                [
                    {
                        "agentid":1,
                        "name":"NAME",
                        "round_logo_url":"xxxxxx",
                        "square_logo_url":"yyyyyy",
                        "appid":1,
                        "privilege":
                        {
                            "level":1,
                            "allow_party":[1,2,3],
                            "allow_user":["zhansan","lisi"],
                            "allow_tag":[1,2,3],
                            "extra_party":[4,5,6],
                            "extra_user":["wangwu"],
                            "extra_tag":[4,5,6]
                        }
                    }
                ]
            },
            "auth_user_info":
            {
                "email":"xxxx@aaa.com",
                "mobile":"1234567890",
                "userid":"aa",
                "name":"xxx",
                "avatar":"http://xxx"
            }
        }
        */
    }

    //获取企业授权信息,该API用于通过永久授权码换取企业微信的授权信息。 永久code的获取，是通过临时授权码使用get_permanent_code 接口获取到的permanent_code。
    /*$app=应用配置前缀简称，例如 ams mss
     * $permanent_code 企业本服务商的永久授权码
     * $auth_corpid 使用服务的企业corpid
     * */
    function get_auth_info($app='',$permanent_code='',$auth_corpid='')
    {
        if($permanent_code==''||$auth_corpid==''||$app=='')
        {
            return false;
        }
        $token=$this->get_suite_token($app);
        $token=json_decode($token);
        if($token->suite_access_token=='')
        {
            return false;
        }
        $wx_config=config('wx');
        $data['suite_id']=$wx_config[$app.'_SuiteID'];
        $data['auth_corpid']=$auth_corpid;
        $data['permanent_code']=$permanent_code;
        $data=json_encode($data);
        $res=model('Http')->httpPost('https://qyapi.weixin.qq.com/cgi-bin/service/get_auth_info?suite_access_token='.$token->suite_access_token,$data);
        return $res;
        /*返回示例
        {
            "errcode":0 ,
            "errmsg":"ok" ,
            "auth_corp_info":
            {
                "corpid": "xxxx",
                "corp_name": "name",
                "corp_type": "verified",
                "corp_square_logo_url": "yyyyy",
                "corp_user_max": 50,
                "corp_agent_max": 30,
                "corp_full_name":"full_name",
                "verified_end_time":1431775834,
                "subject_type": 1，
                "corp_wxqrcode": "zzzzz"
            },
            "auth_info":
            {
                "agent" :
                [
                    {
                        "agentid":1,
                        "name":"NAME",
                        "round_logo_url":"xxxxxx",
                        "square_logo_url":"yyyyyy",
                        "appid":1,
                        "privilege":
                        {
                            "level":1,
                            "allow_party":[1,2,3],
                            "allow_user":["zhansan","lisi"],
                            "allow_tag":[1,2,3],
                            "extra_party":[4,5,6],
                            "extra_user":["wangwu"],
                            "extra_tag":[4,5,6]
                        }
                    }
                ]
            }
        }
        */
    }

    //获取企业token,第三方服务商在取得企业的永久授权码并完成对企业应用的设置之后，便可以开始通过调用企业接口来运营这些应用。其中，调用企业接口所需的access_token获取方法如下。
    /*$app=应用配置前缀简称，例如 ams mss
     * $permanent_code 企业本服务商的永久授权码
     * $auth_corpid 使用服务的企业corpid
     * */
    public function get_corp_token($app='',$permanent_code='',$auth_corpid='')
    {
        if($permanent_code==''||$auth_corpid==''||$app=='')
        {
            return false;
        }
        $token=$this->get_suite_token($app);
        $token=json_decode($token);
        if($token->suite_access_token=='')
        {
            return false;
        }
        $wx_config=config('wx');
        $data['suite_id']=$wx_config[$app.'_SuiteID'];
        $data['auth_corpid']=$auth_corpid;
        $data['permanent_code']=$permanent_code;
        $data=json_encode($data);
        $res=model('Http')->httpPost('https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token='.$token->suite_access_token,$data);
        return $res;
        /*返回示例
        {
            "errcode":0 ,
            "errmsg":"ok" ,
            "access_token": "xxxxxx",
            "expires_in": 7200
        }
        */
    }

    //获取企业微信部门列表
    /*$app=应用配置前缀简称，例如 ams mss
     * $corpid 使用服务的企业corpid
     * */
    public function get_dept_list($app='',$corpid='')
    {
        if($corpid==''||$app=='')
        {
            return false;
        }
        $com=db('company_app')->where(['app'=>$app,'corpid'=>$corpid,'is_use'=>1])->find();
        if($com['id']=='')
        {
            return false;
        }
        $token=$this->get_corp_token($app,$com['permanent_code'],$com['corpid']);
        if(empty($token))
        {
            return false;
        }
        $token=json_decode($token);
        $res=model('Http')->httpGet('https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.$token->access_token);
        return $res;
        /*返回示例
        {
           "errcode": 0,
           "errmsg": "ok",
           "department": [
               {
                   "id": 2,
                   "name": "广州研发中心",
                   "parentid": 1,
                   "order": 10
               },
               {
                   "id": 3
                   "name": "邮箱产品部",
                   "parentid": 2,
                   "order": 40
               }
           ]
        }
        */
    }

    //获取企业微信用户列表
    /*$app=应用配置前缀简称，例如 ams mss
     * $corpid 使用服务的企业corpid
     * $dept_id 部门ID
     * $child 是否递归获取所有子部门用户
     * */
    public function get_user_list($app='',$corpid='',$dept_id=1,$child=1)
    {
        if($corpid==''||$app=='')
        {
            return false;
        }
        $com=db('company_app')->where(['app'=>$app,'corpid'=>$corpid,'is_use'=>1])->find();
        if($com['id']=='')
        {
            return false;
        }

        $token=$this->get_corp_token($app,$com['permanent_code'],$com['corpid']);
        if(empty($token))
        {
            return false;
        }
        $token=json_decode($token);
        $res=model('Http')->httpGet('https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token='.$token->access_token.'&department_id='.$dept_id.'&fetch_child='.$child);
        return $res;
        /*返回示例
            {
                "errcode": 0,
                "errmsg": "ok",
                "userlist": [
                {
                    "userid": "zhangsan",
                    "name": "李四",
                    "department": [1, 2],
                    "order": [1, 2],
                    "position": "后台工程师",
                    "mobile": "15913215421",
                    "gender": "1",
                    "email": "zhangsan@gzdev.com",
                    "isleader": 0,
                    "avatar":           "http://wx.qlogo.cn/mmopen/ajNVdqHZLLA3WJ6DSZUfiakYe37PKnQhBIeOQBO4czqrnZDS79FH5Wm5m4X69TBicnHFlhiafvDwklOpZeXYQQ2icg/0",
                    "telephone": "020-123456",
                    "english_name": "jackzhang",
                    "status": 1,
                    "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
                }
            ]
        }
        */
    }

    //验证开发者URL的系统事件返回信息
    public function check_suite_call_back()
    {
        $wxcpt=model('WXBizMsgCrypt');
        $config=config('wx');
        $wxcpt->set_config($config['suite_token'],$config['suite_encodingAesKey'],$config['corpid']);
        $sVerifyMsgSig = input('get.msg_signature');
        $sVerifyTimeStamp = input('get.timestamp');
        $sVerifyNonce = input('get.nonce');
        $sVerifyEchoStr = input('get.echostr');
        $sEchoStr = "";
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
        if ($errCode == 0)
        {
            //
            // 验证URL成功，将sEchoStr返回
            echo $errCode;
            exit(0);
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
    }
}
?>